import pymysql
from CBD_base.log import log


class MySQL():
    def __init__(self, connect):
        host = connect["host"]
        port = connect["port"]
        user = connect["user"]
        passwd = connect["passwd"]
        database = connect["database"]
        self.db = pymysql.connect(host=host, port=port, user=user, passwd=passwd, database=database)
        self.cursor = self.db.cursor()
        self.log = log.creat_log()

    # 增 - 插入数据,sql中包含数据
    def insert_data(self, sql, *tuple):
        if not tuple:
            try:
                # 执行SQL语句
                self.cursor.execute(sql)
                # 提交到数据库执行
                results = self.cursor.fetchall()
                self.db.commit()
                self.log.info("插入成功")
                self.db.close()
            except:
                # 发生错误时回滚
                self.db.rollback()
                self.log.info("插入失败")
        else:
            try:
                # 执行SQL语句
                self.cursor.execute(sql, *tuple)
                # 提交到数据库执行
                results = self.cursor.fetchall()
                self.db.commit()
                self.log.info("插入成功")
                self.db.close()
            except:
                # 发生错误时回滚
                self.db.rollback()
                self.log.info("插入失败")

    def select_data(self, sql):
        try:
            # 执行SQL语句
            self.cursor.execute(sql)
            # 提交到数据库执行
            results = self.cursor.fetchall()
            self.db.commit()
            self.log.info("查询成功")
            self.db.close()
            return results
        except:
            # 发生错误时回滚
            self.db.rollback()
            self.log.info("插入失败")
